package com.liannong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liannong.entity.Product;
import com.liannong.entity.TransportDetails;
import com.liannong.exception.BusinessException;
import com.liannong.mapper.TransportDetailsMapper;
import com.liannong.service.ProductService;
import com.liannong.service.TransportDetailsService;
import com.liannong.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TransportDetailsServiceImpl extends ServiceImpl<TransportDetailsMapper, TransportDetails> implements TransportDetailsService {

    @Autowired
    private ProductService productService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createTransport(String orderId, String vehicleId, String startLocation, String endLocation, Integer currentTemp) {
        TransportDetails transportDetails = new TransportDetails();
        transportDetails.setOrderId(orderId);
        transportDetails.setVehicleId(vehicleId);
        transportDetails.setStartLocation(startLocation);
        transportDetails.setEndLocation(endLocation);
        transportDetails.setCurrentTemp(currentTemp);
        transportDetails.setStatus("1"); // 默认为运输中
        transportDetails.setCreateTime(LocalDateTime.now());
        return this.save(transportDetails);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTemperature(Long transportId, Integer temperature) {
        TransportDetails transportDetails = this.getById(transportId);
        if (transportDetails == null) {
            throw new BusinessException("运输记录不存在");
        }
        
        transportDetails.setCurrentTemp(temperature);
        return this.updateById(transportDetails);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long transportId, String status) {
        TransportDetails transportDetails = this.getById(transportId);
        if (transportDetails == null) {
            throw new BusinessException("运输记录不存在");
        }
        
        transportDetails.setStatus(status);
        return this.updateById(transportDetails);
    }

    @Override
    public TransportDetails getOrderTransport(String orderId) {
        QueryWrapper<TransportDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<TransportDetails> getVehicleTransports(String vehicleId) {
        QueryWrapper<TransportDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vehicle_id", vehicleId);
        return this.list(queryWrapper);
    }
    
    @Override
    public List<TransportDetails> getAllTransports() {
        return this.list();
    }
    
    @Override
    public Map<Long, Boolean> checkOrderProductsTemperature(String orderId) {
        Map<Long, Boolean> result = new HashMap<>();
        
        // 获取运输记录
        TransportDetails transportDetails = getOrderTransport(orderId);
        if (transportDetails == null) {
            throw new BusinessException("未找到该订单的运输记录");
        }
        
        // 获取当前运输温度
        Integer currentTemp = transportDetails.getCurrentTemp();
        
        try {
            // 尝试将orderId转换为Long类型，可能需要根据系统订单ID格式调整
            Long orderIdLong = Long.parseLong(orderId);
            
            // 获取订单相关的产品
            // 这里假设通过ProductService能获取订单相关的产品列表
            // 实际应用中可能需要通过OrderService获取订单详情，然后查询相关产品
            ProductVO product = productService.getProductDetail(orderIdLong);
            
            if (product != null) {
                Long productId = product.getProductId();
                
                // 检查产品温度范围
                Integer minTemp = product.getMinTemp();
                Integer maxTemp = product.getMaxTemp();
                
                // 判断当前温度是否在产品的安全温度范围内
                boolean isTemperatureSafe = (currentTemp >= minTemp && currentTemp <= maxTemp);
                
                // 如果温度异常，可以在这里添加报警逻辑
                if (!isTemperatureSafe) {
                    // 更新运输记录的报警状态
                    transportDetails.setAlertStatus(1); // 1表示温度异常报警
                    this.updateById(transportDetails);
                }
                
                result.put(productId, isTemperatureSafe);
            }
        } catch (Exception e) {
            // 处理异常，例如orderId不是数字格式，或者获取产品信息失败
            throw new BusinessException("检查产品温度失败: " + e.getMessage());
        }
        
        return result;
    }
} 
 